<template>
  <div name = "doctorInfoPage" class="page">
    <el-row type="flex" :gutter="20" style="margin-top:10px" justify="center">
      <!--基本信息框-->
      <el-col :xl="6" :lg="7">
        <!--信息框容器-->
        <div class="grid-content bg-purple">
          <!--el 卡片容器-->
          <el-card class="box-card" >
            <div slot=":header" class="clearfix">
              <span>医生信息</span>
            </div>
            <div class="doctor-name">
              <span class="doctor-name" >{{doctorData.realName}}</span>
              <el-tag :type=statusStyle class="status-style">{{doctorData.statusName}}</el-tag>
            </div>
            <div class="name-role">
              <span>科室 - {{doctorData.departmentName}}</span>
            </div>
            <!--分界线-->
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">职称：
                <div style="float: right;
                 padding-right:20px;">{{doctorData.titleName}}</div>
              </div>
              <div class="relation-item">所属医院：
                <div style="float: right;
                 padding-right:20px;">{{doctorData.hospitalName}}</div>
              </div>
              <div class="relation-item">医生简介
                <div>
                  {{doctorData.perInfo}}
                </div>
              </div>
            </div>
          </el-card>
          <!--/el 卡片容器-->
        </div>
        <!--/信息框容器-->
      </el-col>
      <!--/基本信息框-->
      <!--候诊信息-->
      <el-col :xl="6" :lg="8">
        <div class="grid-content">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>候诊信息</span>
              <!--当前用户为医生本人时显示-->
              <el-button v-if="outCallBtnVisible"
                         class="button-margin"
                         size="mini" round @click="visitPatient()">出诊</el-button>
            </div>
            <div name="waitingQueueInfo">
              <el-row>
                <div>今日候诊剩余数: {{waitingQueue.maxAppointment}}
                </div>
                <br>
                <div>当前等候人数: {{queueLength}} / {{waitingQueue.maxQueue}}
                  </div>
              </el-row>
              <el-button round @click="waitingQueueVisible = true">查看候诊</el-button>
              <el-button round v-if="lineUpBtnVisible" @click="lineUp">排队就诊</el-button>
              <el-button round v-if="cancelLineUpBtnVisible" @click="cancel">取消候诊</el-button>
              <el-button round v-if="outCallBtnVisible"
                         @click="setQueueBtnVisible = true">候诊信息设置</el-button>
            </div>
          </el-card>

        </div>
      </el-col>
    </el-row>

    <!--候诊队伍表单-->
    <el-dialog title="候诊队伍" :visible.sync="waitingQueueVisible" >
      <el-table :data="patientList" height="250" min-width="200" border>
        <el-table-column type="index" width="75" :index="function(index) {
          return index +1
        }" label="序号">
        </el-table-column>
        <el-table-column property="patientId" label="患者id" width="150"></el-table-column>
        <el-table-column property="realName" label="姓名" width="200"></el-table-column>
      </el-table>
    </el-dialog>

    <!--候诊信息设置-->
    <el-dialog title="候诊信息" :visible.sync="setQueueBtnVisible">
      <el-form :model="waitingQueue" :rules="rules" ref="waitingQueue">
        <el-form-item label="队列最大数" prop="maxQueue">
          <el-input v-model="waitingQueue.maxQueue" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="当日剩余候诊预约" prop="maxAppointment">
          <el-input v-model="waitingQueue.maxAppointment" autocomplete="off"/>
        </el-form-item>

        <el-form-item>
          <el-button @click="onClose">取 消</el-button>
          <el-button type="primary" @click="submitEditQueue('waitingQueue')">确 定</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>

    <!--选择候诊患者信息-->
    <el-dialog titele="选择候诊患者" :visible.sync="selectPatientInfoVisible">
      <el-form :model="patientChoice" ref="selectPatient">
        <el-form-item label="选项" prop="maxQueue">
          <el-select v-model="patientChoice.patientId">
            <el-option v-for="item in myPatientList"
                       :label="item.realName"
                       :value="item.patientId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectPatientInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click.native="submitPatientInfo">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "waitingQueue",
  data() {
    let checkAppointment = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('剩余数不能设为空'));
      }
      if(value < 10 || value > 30)
        return callback(new Error('剩余数区间[10, 30]'))
      callback();
    };
    let checkQueue = (rule, value, callback) =>{
      if (value === '') {
        return callback(new Error('队列最大数不能设为空'));
      }
      if(value < 10 || value > 30)
        return callback(new Error('队列数区间[10, 30]'))
      callback();
    };
    return {
      //候诊队列显示
      waitingQueueVisible: false,
      //设置候诊信息
      setQueueBtnVisible: false,

      //选择候诊患者信息
      selectPatientInfoVisible: false,

      //当前访问用户信息
      userMessage: {
        userId: 0,
        username: '',
        userStatus: 0,
        Status: '',
        isDoctor: false,
      },
      //医生信息
      doctorData: {
        drId: 0,
        hospitalId: 0,
        departmentId: 0,
        realName: '',
        title: 0,
        perInfo: '',
        doctorStatus: '',
        userId: 0,
        hospitalName: '',
        titleName: '',
        statusName: '',
        departmentName: ''

      },
      //候诊队列信息
      waitingQueue: {
        queueId: 0,
        doctorId: 0,
        patientQueue: "",
        maxQueue: 0,
        maxAppointment: 0,
        isOpen: false
      },
      //患者队列
      patientList: [
        {
          patientId: 0,
          realName: '',
        },
        {
          patientId: 0,
          realName: '',
        }
      ],

      //用户的患者信息
      myPatientList: [
        {
          patientId: 0,
          realName: '',
        }
      ],

      //被选择的患者信息
      patientChoice: {
        patientId: 0,
        realName: '',
      },

      queueServer: {
        url: 'ws://localhost:8808/waitingQueue',
        server: ''
      },

      rules: {
        maxAppointment:[
          {required:true, validator: checkAppointment, trigger: 'blur' }
        ],
        maxQueue:[
          {required:true, validator: checkQueue, trigger: 'blur' }
        ]
      },
    };
  },
  computed: {
    queueLength: function(){
      const self = this;
      return self.patientList.length;

    },
    statusStyle: function(){
      let status = "info"
      switch(this.doctorData.doctorStatus){
        case 1: //出诊
          status = "";
          break;
        case 4: //在线
          status = "success";
          break;
        case 6: case 8: //封禁 删除
          status = "danger"
          break;
        case 7:
          status = "warning"
          break;
        default:
          break;
      }
      return status;
    },
    //排队按钮显示
    lineUpBtnVisible: function(){
      let isSeen = !this.userMessage.isDoctor;

      console.log(isSeen);

      return isSeen;
    },
    //出诊按钮显示
    outCallBtnVisible: function(){
      let isSeen = this.userMessage.isDoctor;
      isSeen = isSeen &&
          (this.userMessage.userId === this.doctorData.userId)

      if(isSeen !== true && isSeen !== false)
        isSeen = false;

      return isSeen;
    },
    //取消候诊
    cancelLineUpBtnVisible: function(){
      let isSeen = false;
      const self = this;
      if(self.patientList.length>0) {
        self.patientList.forEach((item, index, arr) => {
          if (Number(item.userBind)
              === Number(self.userMessage.userId)) {
            isSeen = true;
          }
        })
      }
      return isSeen
    }
  },
  //同步请求
  async created() {
    await this.getUserInfo();
    await this.getDoctorInfo();
  },

  destroyed(){
    this.queueServerOnClose();
  },methods: {
    /**
     * 封装异步请求
     * @param api 接口
     * @param dataMap 数据
     */
    myAxios(api,dataMap){
      return new Promise((resolve, reject) => {
        this.$axios({
          method: 'post',
          url: api,
          data: dataMap
        }).then((res) => {
          resolve(res.data);
        }).catch(err => {
          console.log(err)
          reject('error');
        })
      })
    },

    getUserInfo(){
      const self = this;
      console.log("getUserInfo");
      this.$axios.get("api/user/accessUser")
          .then(res=>{
            self.userMessage = res.data.data;
            console.log(1)
          }).catch(err => {
        console.log(err)
        this.$router.push('/login');
      })

    },
    getDoctorInfo(){
      const self = this;
      let reqData = {
        doctorId : Number(localStorage.getItem('visitedDoctorId'))
      };

      self.doctorData= this.$axios
          .post('api/doctor/selectDoctorById',reqData)
          .then((rep) => {
            self.doctorData = rep.data.data;
            console.log(2)

            self.getWaitingQueueInfo();
          }).catch(err => {
            console.log(err)
          })

      console.log("getDoctorInfo")
    },
    getWaitingQueueInfo(){
      const self = this;
      let reqData = {
        method: 'doctorId',
        params: {
          doctorId: self.doctorData.drId
        }
      };

      console.log(reqData.params.valueOf());
      console.log(reqData.valueOf());

      self.$axios
          .post('api/waitingQueue/findQueueInfo',reqData).then(res=>{
        self.waitingQueue = res.data.data[0];
        //console.log(res.data.data[0])
        console.log(3)
        self.initWaitingQueue();
        self.getPatientInfo();
      })
    },
    getPatientInfo(){
      const self = this;
      let data = {
        'patientQueue': self.waitingQueue.patientQueue};

      this.$axios.post('api/waitingQueue/getPatientQueue',data)
          .then(res => {
            self.patientList = res.data.data;

          }).catch(err => {
        console.error("[error]")
        console.log(err);
      })
    },
    getMyPatient(){
      const self = this;
      this.$axios.get('api/patient/accessPatientInfo')
          .then(res =>{
            if(res.data.code === 200)
              self.myPatientList = res.data.data;
            if(res.data.code !== 200){
              self.myPatientList = '';
              console.log('hello');
            }
      }).catch(err=>{

      })

    },
    //排队
    async lineUp() {
      const self = this;
      await self.getMyPatient();
      //判断当前医生是否处于出诊状态
      if(self.doctorData.doctorStatus !== 1){
        self.$message({
          message: '医生非出诊状态',
          type: 'warning'
        })
        return false;
      }
      //判断当前候诊是否关闭
      if(!self.waitingQueue.isOpen){
        self.$message({
          message: '当前候诊已关闭,无法排队',
          type: 'warning'

        })
        return false;
      }

      //检测当前候诊队列人数
      if(self.waitingQueue.maxQueue === self.patientList.length){
        self.$message({
          message: '候诊队列已满',
          type: 'warning'
        })
        return false;
      }
      //检测当前剩余预约人数
      if(self.waitingQueue.maxAppointment === 0){
        self.$message({
          message: '候诊接待数无剩余',
          type: 'warning'
        })
        return false;
      }

      console.log(self.myPatientList)
      //检测当前用户是否绑定患者信息
      if(self.myPatientList.length === 0
          || self.myPatientList[0].patientId === 0){
        self.$message({
          message: '当前账号未绑定患者信息',
          type: 'warning'
        })
        return false;
      }
      //检测是否已排队

      if(self.patientList.length>0) {
        let isOk = true;
        self.patientList.forEach((item, index, arr) => {
          if (Number(item.userBind)
              === Number(self.userMessage.userId)) {
            self.$message({
              message: '当前用户已排队',
              type: 'warning'
            })
            isOk = false;
          }
        })
        if (!isOk) {
          return false;
        }
      }

      self.selectPatientInfoVisible=true;
      self.patientChoice = self.myPatientList[0];
    },

    //提交患者信息
    submitPatientInfo(){
      const self = this;
      let json ={
        userId: self.userMessage.userId,
        patientId: self.patientChoice.patientId,
        queueId: self.waitingQueue.queueId
      }
      self.$axios.post('api/waitingQueue/lineUp',json)
          .then(res =>{
            if(res.data.code === 200)
              self.$message({
                message: '排队就诊成功',
                type: 'success'
              })
      })
      self.selectPatientInfoVisible = false;
    },
    //出诊
    visitPatient(){
      const self = this;
      //判断医生状态
      if(self.doctorData.doctorStatus !== 1) {
        self.$message({
          message: '当前非出诊状态',
          type: 'warning'
        })
        return false;
      }
      //未设置候诊状态
      if(!self.waitingQueue.isOpen){
        self.$message({
          message: '未设置候诊信息',
          type: 'warning'
        })
        return false;
      }
      //创建当前第一位患者的inquiryId
      if(self.patientList.length > 0) {
        let json = {
          doctorId: self.doctorData.drId,
          patientId: self.patientList[0].drId,
        }
        let inquiryObject;
        self.$axios.post('api/inquiry/createInquiry',json)
            .then(res=>{
              inquiryObject = res.data.data;
              this.$router.push({
                path: '/talkRoom/doctor',
                query: {
                  inquiryId: inquiryObject.caseId,
                  userId: self.doctorData.userId
                }
              })
        })
      } else{
        self.$message({
          message: '当前没有患者',
          type: 'warning'
        })
      }
    },
    //取消候诊
    cancel(){
      const self = this;
      let json = {
        queueId: self.waitingQueue.queueId
      }
      self.$axios.post('api/waitingQueue/cancelQueue',json)
          .then(res =>{
          if(res.data.code === 200)
            self.$message({
              message: '取消成功',
              type:'success'
            })
      })
    },

    //------------------webSocket配置--实时更新候诊队列信息-----------------//
    initWaitingQueue() {
      const self = this;
      const serverUrl = self.queueServer.url + "/"
          + self.waitingQueue.queueId
          + "/" + self.userMessage.userId;


      console.log(4)

      self.queueServer.server = new WebSocket(serverUrl);

      let server = self.queueServer.server;
      server.onmessage = this.queueServerOnMessage;
      server.onopen = this.queueServerOnOpen;
      server.onerror = this.queueServerOnError;
      server.onclose = this.queueServerOnClose;
    },
    queueServerOnOpen(){
      console.log("开启候诊信息推送")
    },
    queueServerOnError(e) {
      console.error(e);
    },
    queueServerOnMessage(e) {
      const respData = JSON.parse(e.data);
      const self = this;
      self.waitingQueue = respData;
      console.log(respData.value)
      //更新患者列表
      self.getPatientInfo();

    },
    queueServerSend(Data) {
      let jsonData = JSON.stringify(Data)
      this.queueServer.send(Data);
    },
    queueServerOnClose(e){
      console.log('server close!',e);
    },
    //-----------------------!---------------------------------//
    getPatientList(val){

    },
    //关闭候诊设置
    onClose() {
      this.$emit('close')
    },
    //提交候诊修改
    submitEditQueue(val) {
      const self = this;
      let json = this.waitingQueue;

      this.$refs[val].validate((valid) => {
        if (valid) {
          this.$axios.post('api/waitingQueue/editQueueSetting',json)
              .then(res=>{
                self.waitingQueue = res.data.data;
                self.$message({
                  message: '修改成功',
                  type: 'success'
                })
              })
              .catch(err => {
                self.$message({
                  message: '修改失败',
                  type: 'warning'
                })
          })

        } else {
          return false;
        }
      })
    }

  }
}
</script>

<style scoped>
  /*卡片样式*/
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }

  /*文本样式*/
  .name-role {
    font-size: 16px;
    padding: 5px;
    text-align:center;
  }
  .sender{
    text-align:center;
  }
  .doctor-name{
    text-align: center;
    padding-top:10px;
  }
  .personal-relation {
    font-size: 16px;
    padding: 0px 5px 15px;
    margin-right: 1px;
    width: 100%
  }

  .relation-item {
    /*padding: 12px 5px;*/

  }
  .dialog-footer{
    padding-top:10px ;
    padding-left: 10%;
  }

  /*布局样式*/
  .el-row {
    align-items: center;
    display: flex;
    margin-bottom: 20px;
  }

  .el-row:last-child {
    margin-bottom: 0;
  }

  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  /**
    栅格内容
   */
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;

  }
  /**
  在线图标
   */
  .status-style{
    margin: 5px;
  }
  /**
  出诊按钮
   */
  .button-margin {
    margin: 5px;
  }

  .page{
    height: 100vw;
  }
</style>